package org.admin.entity;


import core.Validate;
import core.validate.Rule;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class BaseDto <T extends BaseDto<T>>{
    protected abstract T inst();
    private final T self = inst();

    protected Map<String, Rule<?>> rules = new HashMap<>();

    public T addRule(Rule<?> rule){
        this.rules.put(rule.key, rule);
        return self;
    }

    public T addRule(Rule<?>[] rules){
        for (Rule<?> rule: rules) {
            this.rules.put(rule.key, rule);
        }
        return self;
    }

    public T addRule(List<Rule<?>> rules){
        for(Rule<?> rule: rules){
            this.rules.put(rule.key, rule);
        }
        return self;
    }

    public Validate<T> validate(String[] keys) {
        List<Rule<?>> rules = new ArrayList<>();

        for(String key: keys){
            if(key.startsWith("*")){
                key = key.substring(1);
                if(!this.rules.containsKey(key)){
                    String ruleKey = key;
                    return new Validate<>(new ArrayList<>(){{
                        add(Rule.String(ruleKey).require("尝试验证未知规则"));
                    }}, self);
                }
                // requires.add(key);
                this.rules.get(key).require("数据未指定");
            }
            rules.add(this.rules.get(key));
        }
        return new Validate<>(rules, self);
    }
}
